package examenes.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import utilitarios.MiConexion;

import examenes.bean.OrdenExamenHcDTO;
import examenes.bean.OrdenExamenesDTO;
import examenes.interfaces.OrdenExamenDAO;

public class MySqlOrdenExamenDAO implements OrdenExamenDAO{

	@Override
	public String generarOE(OrdenExamenesDTO oe) throws SQLException {
		// TODO Auto-generated method stub
		Connection conexion = MiConexion.obtenerConexion();
		CallableStatement call = null;
		String strCodigo = "";
		call = conexion.prepareCall("{call usp_generarOE(?,?,?,?)}");
		call.registerOutParameter(4, java.sql.Types.CHAR);
		call.setString(1, oe.getStrNum_Oae());
		call.setString(2, oe.getUsuario());
		call.setString(3, oe.getTip_ope());
		call.executeUpdate();
		strCodigo = call.getString(4);
		call.close();
		conexion.close();
		return strCodigo;
	}

	@Override
	public List<OrdenExamenHcDTO> listadoOE(String strEstado) {
		// TODO Auto-generated method stub
		List<OrdenExamenHcDTO> oes = new ArrayList<OrdenExamenHcDTO>();
		Connection cn = MiConexion.obtenerConexion();
		try {
			String sql	=	"select oe.num_oe,oae.num_hc,hc.nom_pac,hc.ape_pat_pac,hc.ape_mat_pac " +
					        "from orden_de_examenes oe inner join orden_de__atencion_de__emergencia oae on oe.num_oae=oae.num_oae inner join " +
					        "historia_clinica hc on oae.num_hc=hc.num_hc where estado_oe='Pendiente';";

			PreparedStatement st = cn.prepareStatement(sql);
			ResultSet rs = st.executeQuery();

			while (rs.next()) {
						
				OrdenExamenHcDTO objOeHc = new OrdenExamenHcDTO();
				objOeHc.setStrNroOE(rs.getString(1));
				objOeHc.setNum_Hc(rs.getString(2));
				objOeHc.setNom_Pac(rs.getString(3));
				objOeHc.setApe_Pat_Pac(rs.getString(4));
				objOeHc.setApe_Mat_Pac(rs.getString(5));
				oes.add(objOeHc);
			}
			st.close();
			rs.close();
			cn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return oes;
	}

	@Override
	public void actualizarOE(String strNumOe, String strEstado) throws SQLException {
		// TODO Auto-generated method stub
		Connection cn = MiConexion.obtenerConexion();
		String sql	= "update orden_de_examenes set estado_oe=? where num_oe=?";
		PreparedStatement st = cn.prepareStatement(sql);
		st.setString(1, strEstado);
		st.setString(2, strNumOe);
		st.executeUpdate();
		
		st.close();
		cn.close();
	}

}
